//
//  NavChangePagerController.swift
//  dcloudlive
//
//  Created by zhu xietong on 2020/5/29.
//  Copyright © 2020 douyun. All rights reserved.
//

import Foundation
import soapp
import Eelay
import AsyncDisplayKit


open class NavChangeHeader:JoView{
    public let imgV = UIImageView()
//    let blur:UIVisualEffectView = {
//         if #available(iOS 13.0, *) {
//            let blur = UIVisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterial))
//            return blur
//        } else {
//            let blur = UIVisualEffectView(effect: UIBlurEffect(style: .light))
//            return blur
//        }
//    }()
    
    
    let maskLayer = UIView()
    let ellipseLayer = UIImageView()
    let blur:UIView = UIView()
    public func setSize(size:CGSize) {
        blur.frame = CGRect(x: 0, y: -1000, width: size.width, height: 1000 + size.height + 10)
        imgV.frame = CGRect(x: 0, y: -TP.topHeight, width: size.width, height: size.height + TP.topHeight)
        maskLayer.frame = CGRect(x: 0, y: -10000, width: size.width, height: size.height + 10000)
    }
    
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        ellipseLayer.image = UIImage(named: "ellipseLayer")?.rt_tintedImage(with: ._background)
    }
    open override func addLayoutRules() {
        addSubview(imgV)
        addSubview(maskLayer)
        addSubview(blur)

        let h = 0.046 * Swidth
        eelay = [
            [ellipseLayer,[ee.L.B.R],"\(h)"]
        ]
        ellipseLayer.image = UIImage(named: "ellipseLayer")?.rt_tintedImage(with: ._background)
        ellipseLayer.contentMode = .scaleToFill
        maskLayer.backgroundColor = UIColor(shex: "#0002")
        
        imgV.ui.scheme(scheme: .alioss(limit: .width(120)))
        clipsToBounds = false
        imgV.contentMode = .scaleAspectFit
        imgV.img_url = __images.one_str
    }

    open func observer(scrollView:UIScrollView)  {
        let y = scrollView.contentOffset.y
        if y < 0{
            let h = bounds.height
            let height = h - y + TP.topHeight
            let rect = CGRect(x: 0, y: y - TP.topHeight, width: bounds.width, height: height)
            imgV.frame = rect
        }
    }
}

open class NavChangePagerController: SegmentedPagerViewController,MoAtrributeProtocol,MoRequestTask{
    
    open func  mo_change_localizable(obj: Any?) {
        
    }
    open func mo_set_controller(controller: UIViewController) {
    }
    
    open func mo_model_reload() {
        
    }
    
    open func mo_request_send() {
        
    }
    
    open func mo_detail_reload() {
        
    }
    
    open func createTip()->MoViewTip{
        let tp = MoViewTip()
        tp.superView = self.view
        tp.blur.isHidden = true
        return tp
    }
    
    lazy var tipLayer:MoViewTip = {
        return createTip()
    }()
    
    open func mo_request_alert(msg: String, title: String, bt_title: String) {
        weak var wself = self
        if bt_title.len < 1
        {
            tipLayer.do(action: .loading(message: msg))
            return
        }
        tipLayer.do(action: .tip(message: msg, title: title, action: (bt_title,{
            switch bt_title.escapeHeadTailSpace(){
            case "登录","立即登录":
                EeAuthControl.getUser(finish_block: { (success, msg, user) in
            })
            case "重试","刷新":
                wself?.tipLayer.do(action: .loading(message: nil))
                wself?.mo_request_send()
            default:
                wself?.tipLayer.do(action: .loading(message: nil))
                wself?.mo_request_send()
            }
        })))
       
    }
    
    let segbar = SelectBar()
    var header:NavChangeHeader = NavChangeHeader()
    var controllers:[PageContentViewController] = []
    open override func addLayoutRules() {
//        super.updateViewConstraints()
        NSLayoutConstraint.activate([
            pagerHeader.topAnchor.constraint(equalTo: mainScrollView.topAnchor, constant: topLayoutLength),
            pagerHeader.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            pagerHeader.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            pagerHeader.heightAnchor.constraint(equalToConstant: headerHeight)
        ])
        
        let topConstraint = tabStripView.topAnchor.constraint(equalTo: pagerHeader.bottomAnchor)
        topConstraint.priority = UILayoutPriority(rawValue: 999)
        var safeAreaTopConstraint: NSLayoutConstraint!
        if #available(iOS 11, *) {
            safeAreaTopConstraint = tabStripView.topAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor)
        } else {
            safeAreaTopConstraint = tabStripView.topAnchor.constraint(greaterThanOrEqualTo: topLayoutGuide.bottomAnchor)
        }
        NSLayoutConstraint.activate([
            topConstraint,
            safeAreaTopConstraint,
            tabStripView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tabStripView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tabStripView.heightAnchor.constraint(equalToConstant: tabStripHeight)
        ])
        
        NSLayoutConstraint.activate([
            viewPager.topAnchor.constraint(equalTo: tabStripView.bottomAnchor,constant: 0),
            viewPager.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: .hpadding),
            viewPager.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -.hpadding),
            viewPager.heightAnchor.constraint(equalToConstant: contentHeight)
        ])

        mainScrollView.contentSize = CGSize(width: view.bounds.width, height: topLayoutLength + headerHeight + tabStripHeight + contentHeight + 1)
        viewPager.clipsToBounds = true
    }
    open override var pageWidth: CGFloat {
        return view.bounds.width - 2 * .hpadding
    }


    open override func viewDidLoad() {
        super.viewDidLoad()
        self.header = createHeader()
        headerView = header
        createSegment()
        navigationController?.navigationBar.isTranslucent = true
        

        if #available(iOS 11.0, *) {
            self.mainScrollView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        buildBackBtChangeNavSupport()
        updateNavTransparent(transparent: .yes)
        
        top_style.navBarBgAlpha = 0
        top_style.navTintColor = .clear
        top_style.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.clear]
        rt_disableInteractivePop = false
        
//        pagerHeader.layer.zPosition = -3
        viewPager.backgroundColor = .clear
//        tabStripView.layer.zPosition = -1

    }
    
    
    open func createHeader()->NavChangeHeader {
        let header = NavChangeHeader()
        header.setSize(size: [(Swidth - 2 * .hpadding),headerHeight])
        return header
    }
    
    open func createSegment() {
        segbar.backgroundColor = .clear
        segbar.indicatorColor = ._tint
        segbar.indicatorWidth = 50
        segbar.selectedTextColor = ._foreground
        segbar.items = ["作品","回播","喜欢"]
        segbar.index = 0
        segbar.addTarget(self, action: #selector(selectIndex(sender:)), for: .valueChanged)
        self.segmentedControl = segbar
        self.tabStripHeight = 44
    }
   
    open func buildBackBtChangeNavSupport() {
        backBt.setImage(UIImage(named: "nav_back_shadow"), for: .normal)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBt)
        backBt.addTarget(self, action: #selector(bkButtonPress), for: .touchUpInside)
    }

    @objc public func selectIndex(sender:SelectBar){
        
        viewPager.moveToViewController(at: sender.value, animated: true)
//        co_delay(delay: 0.1) {[weak self] in
        changedTo(index: sender.value)
//        }
    }

    open override func viewControllers(for pagerViewController: SegmentedPagerViewController) -> [PageContentViewController] {
        return self.controllers
    }
    
    
    var index:Int{
        set{
            if newValue != segbar.index{
                segbar.index = newValue
                changedTo(index: newValue)
            }
        }
        get{
            return segbar.index
        }
    }
    func changedTo(index:Int)  {
        
    }
    open override func segmentedPager(didShow childController: PageContentViewController, at index: Int) {
        self.index = index
    }
    
    open override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        super.scrollViewDidScroll(scrollView)
        self.observerScroll(scrollView: scrollView)
        DispatchQueue.main.async(execute: {[weak self] in
            self?.header.observer(scrollView: scrollView)
        })
        
    }

    open var initTopStyle: EeTopStyle{
        var style:EeTopStyle = .default
        style.navBarBgAlpha = 0
        //        style.navBarBgStyle = .color(.blue)
        style.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.clear]
        style.navTintColor = .white
        style.statusBarStyle = .default
        return style
    }

    public let backBt = UIButton(frame: [26,26])
    public weak var __gesture_delegate:UIGestureRecognizerDelegate? = nil

    public var navChangeOffsetY:CGFloat = 120
    public var tranpresentTopStyle = EeTopStyle.navTraspresent()
    public var notranpresentTopStyle = EeTopStyle.default


 
    @objc open func bkButtonPress() {
//        dismissAction()
        _ = self.navigationController?.popViewController(animated: true)
    }




    open func observerScroll(scrollView:UIScrollView)
    {
//        if self.appearStatus != .appeared
//        {
//            return
//        }
        let contentOffsetY = scrollView.contentOffset.y
        let showNavBarOffsetY = navChangeOffsetY - topLayoutGuide.length
        //navigationBar alpha
        if contentOffsetY > showNavBarOffsetY  {
            var navAlpha = (contentOffsetY - (showNavBarOffsetY)) / 40.0
            if navAlpha > 1 {
                navAlpha = 1
            }
            if navAlpha < 0
            {
                navAlpha = 0
            }
            //            self.navigationController?.navigationBar.centerBack.alpha = navAlpha
            top_style.navBarBgAlpha = navAlpha
            if navAlpha > 0.5 {
                top_style.navTintColor = notranpresentTopStyle.navTintColor
                top_style.statusBarStyle = notranpresentTopStyle.statusBarStyle
                top_style.titleTextAttributes = notranpresentTopStyle.titleTextAttributes
                self.updateNavTransparent(transparent: .no)
            }else{
                top_style.navTintColor = tranpresentTopStyle.navTintColor
                top_style.statusBarStyle = tranpresentTopStyle.statusBarStyle
                top_style.titleTextAttributes = tranpresentTopStyle.titleTextAttributes
                self.updateNavTransparent(transparent: .yes)

            }
        }else{


            top_style.navBarBgAlpha = 0
            top_style.navTintColor = tranpresentTopStyle.navTintColor
            top_style.statusBarStyle = tranpresentTopStyle.statusBarStyle
            top_style.titleTextAttributes = tranpresentTopStyle.titleTextAttributes
            self.updateNavTransparent(transparent: .yes)

        }
    }


     open func updateNavTransparent(transparent:NavTransparent) {
         switch transparent {
         case .no:
            
//             let back_icon = UIImage(named: "nav_back_normal")?.rt_tintedImage(with: self.notranpresentTopStyle.navTintColor)
            let back_icon = UIImage(named: "back-indicator")
             top_style.navBarShadow = .color(.clear)
             top_style.navBarShadow = notranpresentTopStyle.navBarShadow
             backBt.setImage(back_icon, for: .normal)
         case .yes:
//             backBt.setImage(UIImage(named: "nav_back_shadow"), for: .normal)
            backBt.setImage(UIImage(named: "back-indicator")?.rt_tintedImage(with: .white), for: .normal)

             top_style.navBarShadow = .color(.clear)
         default:
             break
         }
     }
    
    open override var shouldAutorotate: Bool{
        get{
               return false
        }
    }
       
       open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
           return .portrait
       }
           
       open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
           return .portrait
       }

       
}

